package com.hmall.order.filter;

import com.hmall.common.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("authorization");
        if (auth.equals("2")) {
            log.info("用户id匹配成功，存入ThreadLocal...");
            ThreadLocalUtil.setThreadLocal(auth);
            return true;
        }
        log.error("请求头用户id不匹配！");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("接口调用结束，删除ThreadLocal用户信息");
        ThreadLocalUtil.remove();
    }
}
